const { SuccessModel, ErrorModel } = require("../model/resModel")
const exec = require("../db/mysql")

const getList = (author) => {
  const sql = `select * from blogs where 1=1 and author="${author}"`
  return exec(sql).then(result => {
    return new SuccessModel(result)
  })
}

const getDetail = (id) => {
  const sql = `select * from blogs where 1=1 and id="${id}"`
  return exec(sql).then(result => {
    if (result.length) {
      return new SuccessModel(result)
    } else {
      return new ErrorModel("没有该博客")
    }
  })
}

const newBlog = (body,author) => {
  const { title, content } = body
  const createtime = Date.now()
  const sql = `insert into blogs(title,content,author,createtime)
              value("${title}","${content}","${author}","${createtime}")`
  return exec(sql).then(result => {
    if (result.affectedRows > 0) {
      return new SuccessModel("创建成功")
    } else {
      return new ErrorModel("创建失败")
    }
  })
}

const delBlog = (id) => {
  const sql = `delete from blogs where id=${id}`
  return exec(sql).then(result => {
    if (result.affectedRows > 0) {
      return new SuccessModel("删除成功")
    } else {
      return new ErrorModel("删除失败")
    }
  })
}

const updateBlog = (body) => {
  const { id, title, content } = body
  const createtime = Date.now()
  const sql = `update blogs set title="${title}",content="${content}",createtime="${createtime}" where id="${id}"`
  return exec(sql).then(result => {
    return new SuccessModel(result)
  })
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  delBlog,
  updateBlog
} 